package bundle;

import entities.EducationalLevel;
import entities.EducationalLevelDescription;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EducationalLevelBundle extends ResourceBundle {
     private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("ProyectoPU");
    private static final EntityManager em = factory.createEntityManager();

    protected static final String BASE_NAME = "EducationalLevel.findAll";
    protected static final Control DB_CONTROL = new EducationalLevelBundle.DBControl();

    private Map<String, String> messages;

    public EducationalLevelBundle() {
        setParent(ResourceBundle.getBundle(BASE_NAME, 
            FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL));
    }

    protected EducationalLevelBundle(Map<String, String> messages) {
        this.messages = messages;
    }

    @Override
    protected Object handleGetObject(String key) {
        return messages != null ? messages.get(key) : parent.getObject(key);
    }

    @Override
    public Enumeration<String> getKeys() {
        return messages != null ? Collections.enumeration(messages.keySet()) : parent.getKeys();
    }

    protected static class DBControl extends Control {

        @Override
        public ResourceBundle newBundle
            (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                throws IllegalAccessException, InstantiationException, IOException
        {
            String language = locale.getLanguage();
            Map<String, String> messages= new HashMap<String, String>();
            List<EducationalLevel> educationalLevel=em.createNamedQuery(baseName).getResultList();
            for (EducationalLevel edu : educationalLevel) {
                String description=edu.getDescription();
                for(EducationalLevelDescription eduD: edu.getEducationalLevelDescriptionList()){
                    if(eduD.getLanguage().getCode().equalsIgnoreCase(language)){
                        description=eduD.getDescription();
                        break;
                    }
                }
                messages.put(edu.getIdEducationalLevel().toString(), description);
            }
            return new EducationalLevelBundle(messages);
        }

    }

}